package com.gcxy.conf.exception.handler;

import cn.hutool.core.collection.CollUtil;
import com.gcxy.conf.exception.annotation.GlobalException;
import com.gcxy.conf.exception.exception.IGlobalException;
import com.gcxy.conf.result.R;
import com.gcxy.conf.result.ResultCodeEnum;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 无效的格式异常
 * InvalidFormatException：当潜在问题似乎是要反序列化时值的格式错误，即对数据进行反序列化时异常
 *
 * @author shineTan
 * @date 2022/12/26 14:18
 */
@GlobalException(throwable = InvalidFormatException.class)
public class InvalidFormatExceptionHandler implements IGlobalException<R, InvalidFormatException> {

    @Override
    public R exception(InvalidFormatException throwable, HttpServletRequest request, HttpServletResponse response) {
        return BaseThrowExceptionHandler.exception(throwable, ResultCodeEnum.REQUEST_PARAM_ERROR,
                () -> {
                    List<JsonMappingException.Reference> referenceList = throwable.getPath();
                    String msg = "";
                    if (CollUtil.isNotEmpty(referenceList)) {
                        JsonMappingException.Reference reference = referenceList.get(referenceList.size() - 1);
                        msg = String.format("请求参数名:%s,类型:%s,请求参数值:%s与参数类型不匹配", reference.getFieldName(), throwable.getTargetType().getSimpleName(), throwable.getValue());
                    }
                    return msg;
                }
        );
    }
}
